package com.vanysoft.business.base.tag.service;

import com.baomidou.mybatisplus.plugins.Page;
import com.vanysoft.business.base.tag.controller.demo.UserExport;
import com.vanysoft.business.base.tag.dao.BaseTagMapper;
import com.vanysoft.business.base.tag.entity.TBaseTag;
import com.vanysoft.business.base.user.dao.BaseUserTagsMapper;
import com.vanysoft.business.base.user.entity.TBaseUserTags;
import com.vanysoft.common.utils.string.StringUtil;
import com.vanysoft.framework.constants.DbConstants;
import com.vanysoft.framework.exception.VanySoftBaseException;
import com.vanysoft.framework.messagesource.MessageCodeConstant;
import com.vanysoft.framework.utils.PinYin;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * 项目名称：SharpClaw移动门户
 * 类名称：BaseTagService
 * 类描述：用户分类
 * 创建人：SharpClaw_x
 * 创建时间：2017年5月26日 上午10:09:16
 * 修改人：SharpClaw_x
 * 修改时间：2017年5月26日 上午10:09:16
 * 版本信息：@version 1.0
 * Copyright (c) 2017SharpClaw-版权所有
 * 修改备注：
 */
@Service
@Transactional(readOnly = true)
public class BaseTagService {

    private static String BASE_TAGTYPE_01 = "1";
    private static String BASE_TAGTYPE_00 = "0";
    private static String BASE_TAGTYPE_02 = "2";
    @Autowired
    private BaseTagMapper tBaseTagMapper;
    @Autowired
    private BaseUserTagsMapper baseUserTagsMapper;

    /**
     * Function Name               loadTag
     *
     * @param tagType
     * @return
     * @description 加载用户分类
     * Modify History:              Date             Programmer       Notes
     * ---------        ---------------  ---------
     * 2017年5月26日 上午10:08:37           SharpClaw_x                    Initial
     * *********************************************************************
     */
    public List<Map> loadTag(String tagType, String userId) {
        //tagType 1:公共分类;0:我的分类;2:外部人员分类
        String owner = null;
        if (tagType.equals(BASE_TAGTYPE_01)) {
            owner = DbConstants.TAG_OWNER;
        }
        if (tagType.equals(BASE_TAGTYPE_00)) {
            owner = userId;
        }
        if (tagType.equals(BASE_TAGTYPE_02)) {
            owner = DbConstants.OUTSIDE_TAG_OWNER;
        }
        //查询分类
        List<Map<String, Object>> resultList = tBaseTagMapper.queryTagTree(owner);

        List<Map> treeList = StringUtil.listToTree(resultList, "tagCode", "pid");
        return treeList;
    }


    /**
     * Function Name               loadAllTag
     *
     * @return
     * @description (发送消息查询所有标签 - 消息中心)
     * Modify History:              Date             Programmer       Notes
     * ---------        ---------------  ---------
     * 2017年8月29日 下午2:40:13          SharpClaw_x                     Initial
     * *********************************************************************
     */
    public List<Map> loadAllTag() {

        //查询分类
        List<Map<String, Object>> resultList = tBaseTagMapper.queryAllTagTree();

        List<Map> treeList = StringUtil.listToTree(resultList, "tagCode", "pid");

        return treeList;
    }

    /**
     * Function Name               queryTagUser
     *
     * @param tagCode
     * @param pageIndex
     * @param pageSize
     * @param searchContent
     * @return
     * @description 查询分类人员
     * Modify History:              Date             Programmer       Notes
     * ---------        ---------------  ---------
     * 2017年5月26日 上午11:48:41           SharpClaw_x                    Initial
     * *********************************************************************
     */
    public Map<String, Object> queryTagUser(String tagCode, int pageIndex, int pageSize, String searchContent) {
        Page<Map<String, Object>> page = new Page<>(pageIndex, pageSize);
        List<Map<String, Object>> tagUserList = tBaseTagMapper.queryTagUsers(page, tagCode, searchContent);
        Map<String, Object> map = new HashMap<>();
        map.put("total", page.getTotal());
        map.put("rows", tagUserList);
        return map;
    }

    /**
     * Function Name               queryTagUsers
     *
     * @param tagCode
     * @param searchValue
     * @return
     * @description 不分页访问
     * Modify History:              Date             Programmer       Notes
     * ---------        ---------------  ---------
     * 2017年6月29日 下午5:08:56           SharpClaw_x      Initial
     * *********************************************************************
     */
    public UserExport queryExcelTagUsers(String tagCode, String searchValue) {

        UserExport export = new UserExport();
        export.setUsers(tBaseTagMapper.queryTagUsers(tagCode, searchValue));

        TBaseTag tag = tBaseTagMapper.selectByPrimaryKey(tagCode);
        export.setFileName(tag.getTagName());

        return export;
    }

    /**
     * Function Name               selectTagUser
     *
     * @param tagCode
     * @param userIdStr
     * @return
     * @throws VanySoftBaseException
     * @description 分类选择人员
     * Modify History:              Date             Programmer       Notes
     * ---------        ---------------  ---------
     * 2017年5月26日 下午5:50:47           SharpClaw_x                    Initial
     * *********************************************************************
     */
    @Transactional
    public String selectTagUser(String tagCode, String userIdStr) throws VanySoftBaseException {
        if (StringUtils.isEmpty(userIdStr)) {
            throw new VanySoftBaseException(MessageCodeConstant.RTN_CODE_UNKNOW_ERROR, "userIdStr is null");
        }
        String[] userCode = userIdStr.split(",");
        for (int i = 0; i < userCode.length; i++) {
            TBaseUserTags userTag = new TBaseUserTags();
            userTag.setUserTagId(UUID.randomUUID().toString());
            userTag.setTagCode(tagCode);
            userTag.setUserId(userCode[i]);
            baseUserTagsMapper.insertSelective(userTag);
        }
        return MessageCodeConstant.RTN_CODE_SUCCESS;
    }

    @Transactional
    public Map addTag(String tagType, String tagName, String parentTagCode, String userId) {
        String owner = null;
        //tagType 1:公共分类;0:我的分类;2:外部人员分类
        if (tagType.equals(BASE_TAGTYPE_01)) {
            owner = DbConstants.TAG_OWNER;
        }
        if (tagType.equals(BASE_TAGTYPE_00)) {
            owner = userId;
        }
        if (tagType.equals(BASE_TAGTYPE_02)) {
            owner = DbConstants.OUTSIDE_TAG_OWNER;
        }
        TBaseTag baseTag = new TBaseTag();
        baseTag.setTagCode(UUID.randomUUID().toString());
        baseTag.setTagName(tagName);

        if (StringUtils.isNotEmpty(parentTagCode)) {
            baseTag.setParentTagCode(parentTagCode);
        }

        baseTag.setOwner(owner);
        //简拼
        String searchKeyWord1 = PinYin.getPinYinHeadChar(tagName).toUpperCase();
        baseTag.setSearchKeyWord1(searchKeyWord1);
        //全拼
        String searchKeyWord2 = PinYin.getPingYin(tagName).toUpperCase();
        baseTag.setSearchKeyWord2(searchKeyWord2);
        baseTag.setUpdateTime(new Date());
        baseTag.setIsAvailable(DbConstants.IS_AVAILABLE);

        tBaseTagMapper.insertSelective(baseTag);

        Map map = new HashMap();
        map.put("tagCode", baseTag.getTagCode());
        map.put("TagName", baseTag.getTagName());
        map.put("parentTagCode", parentTagCode);

        return map;
    }

    /**
     * Function Name               modifyTag
     *
     * @param tagCode
     * @param tagName
     * @return
     * @description 修改分类
     * Modify History:              Date             Programmer       Notes
     * ---------        ---------------  ---------
     * 2017年5月26日 下午6:27:48           SharpClaw_x                    Initial
     * *********************************************************************
     */
    @Transactional
    public String modifyTag(String tagCode, String tagName) {
        TBaseTag baseTag = tBaseTagMapper.selectByPrimaryKey(tagCode);
        baseTag.setTagName(tagName);
        //简拼
        String searchKeyWord1 = PinYin.getPinYinHeadChar(tagName).toUpperCase();
        baseTag.setSearchKeyWord1(searchKeyWord1);
        //全拼
        String searchKeyWord2 = PinYin.getPingYin(tagName).toUpperCase();
        baseTag.setSearchKeyWord2(searchKeyWord2);
        baseTag.setUpdateTime(new Date());
        tBaseTagMapper.updateByPrimaryKeySelective(baseTag);
        return MessageCodeConstant.RTN_CODE_SUCCESS;
    }

    /**
     * Function Name               deleteTag
     *
     * @param tagCode
     * @return
     * @throws VanySoftBaseException
     * @description Modify History:              Date             Programmer       Notes
     * ---------        ---------------  ---------
     * 2017年5月26日 下午6:32:26           SharpClaw_x                    Initial
     * *********************************************************************
     */
    @Transactional
    public String deleteTag(String tagCode) throws VanySoftBaseException {
        if (childTag(tagCode)) {
            throw new VanySoftBaseException(MessageCodeConstant.UserAndRoleException.RTN_CODE_CHILDTAG_CODE);
        }
        TBaseTag baseTag = tBaseTagMapper.selectByPrimaryKey(tagCode);
        baseTag.setIsAvailable(DbConstants.IS_NOT_AVAILABLE);
        tBaseTagMapper.updateByPrimaryKeySelective(baseTag);
        //删除人员分类关系
        tBaseTagMapper.deleteUserTags(tagCode);
        return MessageCodeConstant.RTN_CODE_SUCCESS;
    }

    private boolean childTag(String tagCode) {
        boolean tag = false;
        List<Map> reslutList = tBaseTagMapper.queryChildTag(tagCode);
        if (reslutList != null && reslutList.size() > 0) {
            tag = true;
        }
        return tag;
    }

    /**
     * Function Name               deleteTagUser
     *
     * @param tagCode
     * @param userCodes
     * @throws VanySoftBaseException
     * @description 批量删除人员
     * Modify History:              Date             Programmer       Notes
     * ---------        ---------------  ---------
     * 2017年6月19日 上午11:57:14           SharpClaw_x                    Initial
     * *********************************************************************
     */
    @Transactional
    public void deleteTagUser(String tagCode, String userIds) throws VanySoftBaseException {
        if (StringUtils.isEmpty(userIds)) {
            throw new VanySoftBaseException(MessageCodeConstant.RTN_CODE_UNKNOW_ERROR, "userIds is null");
        }

        String[] userCode = userIds.split(",");
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("tagCode", tagCode);
        map.put("userId", userCode);
        baseUserTagsMapper.deleteTagUserBytagCode(map);

    }

}
